<template>
	<view class="container">
		<TopNav title="请选择你的服务城市" bg-color="#fff"></TopNav>
		<view class="main">
			<view class="m-b20 position-city">
				<text class="text-gray f-s12 m-r10">定位当前城市</text>
				<view class="m-t12 flex justify-between align-center">
					<view class="flex align-center">
						<image src="/static/images/login/location.png" class="width-20 height-20 m-r6 self-center"
							mode="widthFix">
						</image>
						<text class="f-s15 text-bold p-l8">{{address}}</text>
					</view>
					<view class="text-theme f-s14 line-height20" hover-class="pressed" @click="handleSetPosition(true)">
						<text>重新定位</text>
					</view>
				</view>

			</view>
		<!-- 	<view class="p-tb16">
				<view class="m-b10">
					<text class="f-s14 text-gray">国内热门城市</text>
				</view>
				<view class="grid"
					:style="{'grid-template-rows':`repeat(${Math.ceil(hotCityList.length / 4)}, 64rpx)`}">
					<view class="grid-item" v-for="item in hotCityList" :key="item.id"
						:class="{'grid-item-active':checkSelected(item.id)}">
						<text>{{item.label}}</text>
					</view>
				</view>
			</view> -->
			<view class="m-b10 line"></view>
			<view class="m-b10 index-container overflow-hidden">
				<u-index-list activeColor="#FE3F59" :indexList="indexList">
					<template v-for="(item, index) in orderCityList">
						<u-index-item>
							<u-index-anchor :text="item.key" bgColor="#fff" class=""></u-index-anchor>
							<view class="" :class="{'city-active':checkSelected(cityItem.id)}"
								v-for="cityItem of item.value" :key="cityItem.id">
								<view class="p-tb10" @click="select = cityItem.id">{{cityItem.site_area_name}}</view>
							</view>
						</u-index-item>
					</template>
				</u-index-list>
			</view>
		</view>
		<view class="fixed-bottom bg-white p-lr16">
			<view class="self-btn full-width m-t6" hover-class="pressed" @click="handleSelectCity">
				<text>确认</text>
			</view>
		</view>
		<Empty :show="orderCityList.length === 0"></Empty>
		<Modal :show.sync="modalShow" title="提示" :cancelBtn="false" confirmText="我知道了" content="城市切换成功！\n请注意：服务项目单价可能因为城市切换发生变化"
			@confirm="handleModalConfirm">
			<!-- <view>
				<text class="text-bold line-height42 f-s32">{{formatPhoneNumber(userInfo.order_mobile)}}</text>
			</view> -->
		</Modal>
		<Toast></Toast>
	</view>
</template>

<script>
	import {
		cityList,
		setCity,
		hotCityList,
		orderCityList
	} from "@/api/mine/service.js"
	import mixins from "@/mixins";
	import Empty from '@/components/empty/index.vue'
	import {
		async
	} from "regenerator-runtime";
	import Modal from "@/components/modal/index.vue"
	export default {
		mixins: [mixins],
		components: {
			Empty,
			Modal
		},
		data() {
			return {
				modalShow:false,
				address: '',
				select: '',
				indexList: [],
				hotCityList: [],
				orderCityList: [],
				list: [],
				queryParams: {
					title: '',
					page: 1,
					limit: 10
				}
			};
		},
		async onLoad(query) {
			if (query.city_name) {
				this.select = await this.findIdByAreaName(query.city_name)
			}
			// this.getHotCityList()
			this.getOrderCityList()
			this.handleSetPosition()
		},
		methods: {
			handleModalConfirm(){
				this.$tab.navigateBack()
			},
			// 更新位置信息
			handleSetPosition(pressed) {
				this.address = "正在定位..."
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						let {
							province,
							city
						} = res.address;
						if (this.address)
							this.address = city || province
						if (pressed && this.address) {
							// 手动定位，匹配城市
							(async () => {
								this.select = await this.findIdByAreaName(this.address)
							})()
						}
					},
					fail: () => {
						this.address = '定位失败'
					}
				});
			},
			checkSelected(id) {
				return this.select === id
			},

			async getOrderCityList() {
				await orderCityList().then(res => {
					let {
						data
					} = res
					this.orderCityList = data || []
					this.indexList = data.map(item => {
						return item.key
					})
				})
			},
			async findIdByAreaName(areaName) {
				if (this.orderCityList.length === 0) {
					await this.getOrderCityList()
				}
				let data = this.orderCityList
				for (const item of data) {
					// 处理 value 是数组的情况（如 "b" 键）
					if (Array.isArray(item.value)) {
						for (const area of item.value) {
							if (area.site_area_name === areaName) {
								return area.id;
							}
						}
					}
					// 处理 value 是对象的情况（如 "c" 和 "s" 键）
					else if (typeof item.value === 'object' && item.value !== null) {
						for (const key in item.value) {
							const area = item.value[key];
							if (area.site_area_name === areaName) {
								return area.id;
							}
						}
					}
				}
				return null; // 如果未找到返回 null
			},
			getHotCityList() {
				hotCityList().then(res => {
					let {
						data
					} = res
					this.hotCityList = data.map(item => {
						return {
							label: item.site_area_name,
							id: item.id
						}
					})
				})
			},
			getCityList() {
				cityList().then(res => {
					let {
						data: {
							list,
							count,
							total
						}
					} = res
					this.total = count || 0
					this.pageTotal = total || 0
					if (this.queryParams.page === this.pageTotal) this.loadmoreStatus = 'nomore'
					if (this.queryParams.page === 1) {
						this.list = list
					} else if (this.queryParams.page < this.pageTotal) {
						this.list = this.list.concat(list)
					}
				})
			},
			handleSearch() {
				this.queryParams.page = 1
				this.getList()
			},
			handleSelectCity() {
				if (!this.select) {
					this.$toast("请选择你的服务城市")
					return
				}
				this.$modal.loading('正在设置').then(() => {
					setCity({
						website_id: this.select
					}).then(res => {
						this.$store.dispatch('GetInfo').then(() => {
							this.$modal.closeLoading()
							this.modalShow = true
							// this.$toast('城市切换成功！\n请注意：服务项目单价可能因为城市切换发生变化').then(() => {
							// 	this.$tab.navigateBack()
							// })
						}).catch(() => this.$modal.closeLoading())

					}).catch(() => this.$modal.closeLoading())
				})
			},
		}
	}
</script>
<style lang="scss">
	@import '@/common/css/var.scss';

	page {
		background-color: #fff;
		@include fixed-bottom;
	}
	.position-city{
		position: sticky;
		@include sticky-top;
		width: 100%;
		background-color: #fff;
	}
</style>
<style lang="scss">
	.container {
		padding: 32rpx;
		
		.grid {
			display: grid;
			grid-template-columns: repeat(4, 152rpx);
			// grid-template-rows: repeat(3, 64rpx);
			grid-row-gap: 26rpx;
			grid-column-gap: 24rpx;

			// grid-template-columns: repeat(12,1fr);
			.grid-item {
				background-color: #F0F1F2;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 400;
				font-size: 24rpx;
			}

			.grid-item-active {
				background-color: #FE3F59;
				color: #fff;
			}
		}

		.index-container {
			// @include fixed-bottom;
			// padding: 0 32rpx;
		}

		::v-deep .u-index-anchor {
			top: -1px;
		}

		.tag {
			padding: 8rpx 8rpx 8rpx 12rpx;
			background-color: #EBECED;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			line-height: 24rpx;
			margin-right: 10rpx;

			&:last-child {
				margin-right: 0;
			}

			image {
				width: 28rpx;
				height: 28rpx;
				margin-left: 12rpx;
			}
		}
	}

	.city-active {
		background-color: #fe3f590a;
		padding-left: 8rpx;
		color: #FE3F59;
	}

	::v-deep .u-index-anchor {
		border-bottom: none !important;
		padding-left: 0 !important;

		.u-index-anchor__text {
			color: #202020;
			font-size: 24rpx !important;
		}
	}
</style>